package com.tianji.remark.Task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianji.common.utils.CollUtils;
import com.tianji.remark.constant.RedisConstnt;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.service.ILikedRecordService;
import com.tianji.remark.mapper.LikedRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

@Component
@Slf4j
@RequiredArgsConstructor
public class TaskForLike {
    private final ILikedRecordService recordService;
    @Autowired
    private LikedRecordMapper likedRecordMapper;
    private static final List<String> BIZ_TYPES = List.of("QA", "NOTE");
    @Value("${tj.mq.max-size}")
    private Integer max_count;
    private final StringRedisTemplate redisTemplate;

    @Scheduled(fixedDelay = 30000)
    public void taskForLike() {
        //1.定时发送点赞数的数据给相应队列
        log.info("定时发送点赞数的数据给相应队列");
        for (String bizType : BIZ_TYPES) {
            recordService.readLikeTiemsAndSendMessage(bizType,max_count);
        }
    }

    //定时持久化记录到数据库
    @Scheduled(cron = "0 0 3 1 * *")
    public void StoreToDB(){
        log.info("定时持久化记录到数据库");
        try {
                // 加表锁 - 锁住整张表
                likedRecordMapper.lockTable();
                //1.先把现有的数据库给清空
                recordService.remove(new LambdaQueryWrapper<>());
                ScanOptions options = ScanOptions.scanOptions()
                        .match("*") // 匹配所有键
                        .count(100) // 每次迭代数量
                        .build();
                Cursor<String> cursor = redisTemplate.scan(options);
                Set<String> keys = new HashSet<>();
                while (cursor.hasNext()) { //todo 当游标回到0时,这个方法会返回false
                    String key = cursor.next(); //将返回的100个左右的键逐个处理
                    // 处理键...
                    if(Pattern.matches(RedisConstnt.LIKE_BIZ_KEY_PREFIX+"*",key)){
                        keys.add(key);
                    }
                }
                cursor.close(); // 释放资源
                if(CollUtils.isNotEmpty(keys)){
                    //取出对应键的所有值并做持久化处理
                    for (String key : keys) {
                        Set<String> members = redisTemplate.
                                opsForSet().members(key);
                        //分离出用户id和业务类型,业务Id
                        String bizType = key.split(":")[1];
                        Long userId = Long.parseLong(key.split(":")[0]);
                        String bizId = key.split(":")[3];
                        LikedRecord record = LikedRecord.builder()
                                .bizId(Long.parseLong(bizId))
                                .bizType(bizType)
                                .userId(userId)
                                .createTime(LocalDateTime.now())
                                .updateTime(LocalDateTime.now())
                                .build();
                        recordService.save(record);
                        //删除键 - 减轻redis的压力
//                        redisTemplate.delete(key);
//                        log.info("删除键:{}",key);
                }
            }
        } finally {
            // 释放表锁
            likedRecordMapper.unlockTable();
        }
    }
}